﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace Siva.CBC.Barnacle.ashx
{
    /// <summary>
    /// searchRecordHandler 的摘要说明
    /// </summary>
    public class searchRecordHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string searchTerm = context.Request.Form["content"];
            cunReturn returnModel = new cunReturn();
            returnModel.Success = false;
            
            string sql = "select filename,fullname,createtime from records where filename like '%{0}%' order by createtime desc";

            List<RecordModel> list = new List<RecordModel>();
            DataTable dt = SqlHelper.ExecuteDataTable(string.Format(sql, searchTerm));

            if (dt.Rows.Count<1)
            {
                returnModel.Message = "未查询到记录";
            }
            else
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    RecordModel model = new RecordModel()
                    {
                        filename = dt.Rows[i][0].ToString(),
                        fullname = dt.Rows[i][1].ToString(),
                        createtime = DateTime.Parse(dt.Rows[i][2].ToString())
                    };
                    list.Add(model);
                }
                returnModel.Success = true;
                
                returnModel.Data = JsonSerialize.Serialize(list);
            }

           

            context.Response.Write(JsonSerialize.Serialize(returnModel));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private void SearchDirectory(DirectoryInfo directoryInfo, Regex searchRegex, List<string> files)
        {
            FileInfo[] filesInDir = directoryInfo.GetFiles();
            foreach (FileInfo file in filesInDir)
            {
                if (searchRegex.IsMatch(file.Name))
                {
                    files.Add(file.FullName);
                }
            }

            DirectoryInfo[] dirsInDir = directoryInfo.GetDirectories();
            foreach (DirectoryInfo dir in dirsInDir)
            {
                SearchDirectory(dir, searchRegex, files);
            }
        }  
    }
}